import { watch, ref, onMounted } from 'vue'
import { message } from 'ant-design-vue'
import { post } from '@/utils/request'
import { formatAmount, formatDate } from '@/utils/format.js'
/**
 * @name: 获取表头
 */
export default function (props) {
  const columnData = ref([{}]) //默认值为[{}]，防止表格渲染时报错
  const columnLoading = ref(false)

  //获取表头
  const getColumns = async () => {
    columnLoading.value = true
    const { code, data } = await post('/common/util/getTableMappingCloumnList', { id: props.columnCode })
    columnLoading.value = false
    if (code !== 0) return
    if (data.length > 0) {
      // 排除excludeColumns列和隐藏列
      const columnCode = JSON.parse(localStorage.getItem('columnCode') || '[]')
      localStorage.setItem('columnCode', JSON.stringify([...columnCode, props.columnCode]))
      columnData.value = data.filter((item, index) => {
        item.width = parseToNumber(item.width)
        item.resizable = true
        item.customRender = item.format ? (record) => formatValue(record) : undefined
        item.sorter = item.sorter ? (a, b) => sorterFunc(a[item.dataIndex], b[item.dataIndex]) : undefined
        if (index === data.length - 1) {
          // item.customFilterDropdown = true
        }
        return !props.excludeColumns.includes(item.dataIndex) && !item.isHide
      })
    } else {
      message.error(`获取表头【${props.columnCode}】失败`)
    }
  }
  function parseToNumber(str) {
    const num = parseFloat(str)
    if (!isNaN(num)) {
      return num
    } else {
      return undefined
    }
  }
  const formatValue = ({ text, column }) => {
    switch (column.format) {
      case '两位小数':
        return formatAmount(text, 2, false)
      case '三位小数':
        return formatAmount(text, 3, false)
      case '五位小数':
        return formatAmount(text, 5, false)
      case '长日期':
        return formatDate(text, 'YYYY-MM-DD HH:mm:ss')
      case '短日期':
        return formatDate(text, 'YYYY-MM-DD')
      default:
        return text
    }
  }
  watch(
    () => props.columnCode,
    () => {
      props.columnCode && getColumns()
    }
  )
  //排序
  const sorterFunc = (a, b) => {
    if (typeof a === 'string') {
      return a.localeCompare(b)
    } else if (typeof a === 'number') {
      return a - b
    }
  }
  onMounted(() => {
    if (props.columnCode) {
      getColumns()
    } else {
      columnData.value = props.columns.map((item) => ({ ...item, resizable: true }))
    }
  })
  return { columnLoading, columnData }
}
